// src/controllers/category.ts
import { Context } from 'koa'
import categoryService from '../services/category'

export class CategoryController {
  // 创建分类
  async create(ctx: Context) {
    const categoryData = ctx.request.body
    const category = await categoryService.create(categoryData)
    ctx.status = 201
    ctx.body = {
      success: true,
      data: category,
      message: '分类创建成功'
    }
  }

  // 更新分类
  async update(ctx: Context) {
    const { id } = ctx.params
    const updateData = ctx.request.body
    const category = await categoryService.update(parseInt(id), updateData)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: category,
      message: '分类更新成功'
    }
  }

  // 删除分类
  async delete(ctx: Context) {
    const { id } = ctx.params
    await categoryService.delete(parseInt(id))
    ctx.status = 200
    ctx.body = {
      success: true,
      message: '分类删除成功'
    }
  }

  // 删除分类及其所有子分类
  async deleteWithChildren(ctx: Context) {
    try {
      const { id } = ctx.params
      await categoryService.deleteWithChildren(parseInt(id))
      ctx.status = 200
      ctx.body = {
        success: true,
        message: '分类及其子分类删除成功'
      }
    } catch (error) {
      throw error
    }
  }

  // 查询单个分类
  async findOne(ctx: Context) {
    const { id } = ctx.params
    const category = await categoryService.findOne(parseInt(id))
    ctx.status = 200
    ctx.body = {
      success: true,
      data: category,
      message: '查询成功'
    }
  }

  // 查询所有分类
  async findAll(ctx: Context) {
    const { type } = ctx.query
    const categories = await categoryService.findAll(type as string | undefined)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: categories,
      message: '查询成功'
    }
  }

  // 根据父分类ID查询子分类
  async findByParentId(ctx: Context) {
    const { parentId } = ctx.params
    const parentIdNum = parentId === 'null' ? null : parseInt(parentId)
    const categories = await categoryService.findByParentId(parentIdNum)
    ctx.status = 200
    ctx.body = {
      success: true,
      data: categories,
      message: '查询成功'
    }
  }
}

export const categoryController = new CategoryController()
